#include "stdafx.h"
#include "TaskBuilder.h"

TaskBuilder::TaskBuilder( double l, double r, int n, FunctionType f, double lgu, double rgu, bool autoGU ): left(l), right(r), numberGridPoints(n), function(f), leftGU(lgu), rightGU(rgu)
{
// Get memory for x and y
	x = new double[numberGridPoints + 1];
	double* y = new double[numberGridPoints + 1];

// Initialize grid
	for (int i=0; i<numberGridPoints+1; i++)
	{
		x[i] = left + (right - left) * i / (numberGridPoints);
		y[i] = function.getF(x[i]);
	}

	if (autoGU)
	{
		leftGU = function.getDiffTwo(left);
		rightGU = function.getDiffTwo(right);
	}

// Building spline
	spline.build_spline(x, y, leftGU, rightGU, numberGridPoints);
	delete[] y;
}

TaskBuilder::~TaskBuilder()
{
	delete[] x;
}

void TaskBuilder::getPrecision( int gridFrequency, double& x_max, double& max)
{
	int numTestGridPoints = gridFrequency * numberGridPoints;
	max = 0.0;
	double test_x;

	for (int i=0; i<numTestGridPoints; i++)
	{
		test_x = left + (right - left) * i / (numTestGridPoints - 1);
		if (abs(function.getF(test_x) - spline.getF(test_x)) > max)
		{
			max = abs(function.getF(test_x) - spline.getF(test_x));
			x_max = test_x;
		}
	}
}

void TaskBuilder::getPrecisionDiffOne( int gridFrequency, double& x_max, double& max )
{
	int numTestGridPoints = gridFrequency * numberGridPoints;
	max = 0.0;
	double test_x;

	for (int i=0; i<numTestGridPoints; i++)
	{
		test_x = left + (right - left) * i / (numTestGridPoints - 1);
		if (abs(function.getDiffOne(test_x) - spline.getDiffOne(test_x)) > max)
		{
			max = abs(function.getDiffOne(test_x) - spline.getDiffOne(test_x));
			x_max = test_x;
		}
	}
}

void TaskBuilder::getPrecisionDiffTwo( int gridFrequency, double& x_max, double& max )
{
	int numTestGridPoints = gridFrequency * numberGridPoints;
	max = 0.0;
	double test_x;

	for (int i=0; i<numTestGridPoints; i++)
	{
		test_x = left + (right - left) * i / (numTestGridPoints - 1);
		if (abs(function.getDiffTwo(test_x) - spline.getDiffTwo(test_x)) > max)
		{
			max = abs(function.getDiffTwo(test_x) - spline.getDiffTwo(test_x));
			x_max = test_x;
		}
	}
}

double TaskBuilder::getDifference( double x )
{
	return abs(function.getF(x) - spline.getF(x));
}

double TaskBuilder::getDifferenceDiffOne( double x )
{
	return abs(function.getDiffOne(x) - spline.getDiffOne(x));
}

double TaskBuilder::getDifferenceDiffTwo( double x )
{
	return abs(function.getDiffTwo(x) - spline.getDiffTwo(x));
}

